#!/usr/bin/perl

# List of all machines are listed under HOME/.farm_machines.txt
my $CONFIG = ".farm_machines.txt";
my @machines = ();

open IN, "<", $ENV{"HOME"}."/".$CONFIG or die "Error: can not open $CONFIG";
while(<IN>)
{
	chomp;
	next if /^\s*$/;
	push @machines, $_;
}
close IN;

my $highest_index = $#machines;

sub check_if_node_is_up
{
	my ($node) = @_;
	my $result = 0;

	# close output pipe and error pipe
	open(OLDERR,     ">&", \*STDERR);
	open(OLDSTDOUT,     ">&", \*STDOUT);
	open(STDOUT, '>>', "/dev/null");
	open(STDERR, '>>', "/dev/null");
	
	# test node
	system("ssh $node ls");
	$result = $? == 0 ? 1 : 0;

	# restore output pipe and error pipe
	open(STDERR, ">&OLDERR");
	open(STDOUT, ">&OLDSTDOUT");

	return $result;
}

sub get_a_random_machine
{
	my $random = int(rand($highest_index));
	my $result = $machines[$random];
        my $valid = &check_if_node_is_up($result);
	if ($valid == 0)
	{
		&get_a_random_machine();
	}
	else
	{
		return $result;
	}
}

sub get_all_machines
{
	my @result = ();
	foreach my $i (@machines)
	{
		if (&check_if_node_is_up($i))
		{
			push @result,$i;
		}
	}
	return @result;
}

1;
